<template>


  <div style="background: #fff; width: 600px; margin: 60px auto; padding: 20px 50px;">
    <h1 style="text-align: center; margin: 30px auto;">用户注册</h1>
    <el-form ref="form" :rules="rules" :model="form" label-width="100px" class="demo-ruleForm">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" type="password"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="form.confirmPassword" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('form')">注册</el-button>
        <el-button @click="resetForm('form')">重置</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        username: 'test',
        password: '123456',
        confirmPassword: '123456',
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在6-20个字符之间', trigger: 'blur' },
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.form.password) {
                callback(new Error('两次输入的密码不一致'));
              } else {
                callback();
              }
            },
            trigger: 'blur',
          },
        ],
      },
    };
  },
  methods: {
    submitForm(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          // 在这里可以添加提交表单的代码
          let url = 'http://localhost:9081/user/register';
          console.log('url = ' + url);

          let formData = this.qs.stringify(this.form);
          console.log('formData = ' + formData);

          this.axios.post(url, formData).then((response) => {
            let responseBody = response.data;
            console.log(responseBody);
            if (responseBody.state == 20000) {
              this.$message({
                showClose: true,
                message: '登录成功！',
                type: 'success'
              });
              this.$router.push( '/user/login')

            } else {
              this.$message({
                showClose: true,
                message: responseBody.message,
                type: 'error'
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    resetForm(form) {
      this.$refs[form].resetFields();
    },
  },
};
</script>
<style>
body {
  background: #FFFFFF;
}
</style>